package com.bloody.android.Bluetooth;

import java.util.ArrayList;

import com.bloody.android.BloodyCrusadeGame;
import com.bloody.android.CharactersSelection;
import com.bloody.android.R;
import com.bloody.android.RoundView;
import com.bloody.android.Map.Map;
import com.bloody.android.Observer.Observer;
import com.bloody.android.R.string;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

abstract class MBT extends Activity implements Observer {
    // Intent request codes
    public static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    public static final int CHARACTERS_SELECTED = 2;
    public static final int REQUEST_ENABLE_BT = 3;
    
    private static final int JOIN = 4;
    
    public static final String TOAST = "toast";
    public static final String DEVICE_NAME = "device_name";


    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothService mService = null;
    
    private Bundle mBundle;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mBundle = new Bundle();

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        }
    }
    
    public Bundle getBundle(){
    	return mBundle;
    }
    
    
    public static int getRequestConnectDeviceSecure() {
		return REQUEST_CONNECT_DEVICE_SECURE;
	}

	public static int getRequestEnableBt() {
		return REQUEST_ENABLE_BT;
	}
    
    @Override
    public void onStart() {
        super.onStart();

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (mService == null) setup();
        }
    }
    
    public BluetoothAdapter getmBluetoothAdapter() {
		return mBluetoothAdapter;
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE_SECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data);
            }
            else
            {
            	onBackPressed();
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a session
                setup();
            } else {
                // User did not enable Bluetooth or an error occurred
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
            break;
        case CHARACTERS_SELECTED:
        	Bundle info = data.getExtras();
        	sendMessage(info);
        	break;
        }
    }
	
	public void sendMessage(Bundle bundle){
		Log.d("DEBUG", "SEND INFORMATION");
		ArrayList<String> myCharacters = bundle.getStringArrayList("myCharacters");
        ArrayList<Integer> myCharactersRow = bundle.getIntegerArrayList("myCharactersRow");
        ArrayList<Integer> myCharactersCol = bundle.getIntegerArrayList("myCharactersCol");
        String msg= "";
        for (int i=0; i<myCharacters.size(); i++){
        	if (i==0)
        		msg+=myCharacters.get(i)+" "+myCharactersRow.get(i)+" "+myCharactersCol.get(i);
        	else
        		msg+=" "+myCharacters.get(i)+" "+myCharactersRow.get(i)+" "+myCharactersCol.get(i);
        }
    	mService.write("characters", msg);
    	mBundle.putAll(bundle);
	}
	
	public void characterSelection(Bundle bundle){
		Intent intent = new Intent(this.getApplicationContext(), CharactersSelection.class);
		intent.putExtras(bundle);
		startActivityForResult(intent, CHARACTERS_SELECTED);
	}
    
	private void connectDevice(Intent data) {
        // Get the device MAC address
        String address = data.getExtras()
            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mService.connect(device);
    }
    
    @Override
    public synchronized void onResume() {
        super.onResume();

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mService.getState() == BluetoothService.STATE_NONE) {
              // Start the Bluetooth services
              mService.start();
            }
        }
    }
    
    private void setup() {
        
        // Initialize the BluetoothChatService to perform bluetooth connections
        mService = BluetoothService.getInstance(this);
        mService.delAllObserver();
        mService.addObserver(this);
        //mService.setMBT(this);

    }
    /*
    public void connectionFailed(){
    	Toast.makeText(getApplicationContext(), "Unable to connect device",
                Toast.LENGTH_SHORT).show();
    	finish();
    }*/
    
    public void launchBcg(){
    	//mService.setMBT(null);
    	mService.addObserver(this);
    	Intent intent = new Intent(this, BloodyCrusadeGame.class);
    	intent.putExtras(mBundle);
    	Log.d("DEBUG", "Launch Activity");
    	startActivity(intent);
    	finish();
    }
    
    public void setCharacters(Bundle bundle){
    	String[] tmp = bundle.getStringArray("datas");
		ArrayList<String> characters = new ArrayList<String>();
		ArrayList<Integer> charactersRow = new ArrayList<Integer>();
		ArrayList<Integer> charactersCol = new ArrayList<Integer>();
		for(int i=0 ; i<tmp.length ; i+=3) {
	    	characters.add(tmp[i]);
	    	charactersRow.add(Integer.parseInt(tmp[i+1]));
	    	charactersCol.add(Integer.parseInt(tmp[i+2]));
		}

		mBundle.putStringArrayList("otherCharacters", characters);
    	mBundle.putIntegerArrayList("otherCharactersRow", charactersRow);
    	mBundle.putIntegerArrayList("otherCharactersCol", charactersCol);
		Log.d("DEBUG", "RECEIVE INFO");
    }
    
    @Override
	public void onBackPressed (){
    	Log.d("DEBUG", "finish fait");
        mService.stop();
    	finish();
	}

	public void setBundle(Bundle bundle) {
		mBundle = bundle;
	}
	
	@Override
	public void update(Bundle bundle) {
		if(bundle.getString("type").equalsIgnoreCase("characters"))
			setCharacters(bundle);
		else if(bundle.getString("type").equalsIgnoreCase("connectionfailed"))
		{
	    	runOnUiThread(new Runnable() {
	            @Override
	            public void run()
	            {
	    	    	Toast.makeText(getApplicationContext(), "Unable to connect device",
	    	    			Toast.LENGTH_SHORT).show();
	            }
	         });

	    	finish();
		}
	}
}